//#define _XOPEN_SOURCE  1
#define _SVID_SOURCE  1
//#define _POSIX_SOURCE  1
//#define _BSD_SOURCE  1
#include "../include/structure.h"
#include "../include/queue.h"

int pipe_fd[2];

void handler(int num){
	write(pipe_fd[1], "1", 1);
	printf("2 signal come!\n");
}


int main(int argc, char* argv[]){
	pipe(pipe_fd);
	if(fork() != 0){
		// parent
		signal(2, handler);
		wait(NULL);

		printf("所有东西都亖了\n");
		exit(0);

	}

	setpgid(0, 0);

	pool_t pool;
	initPool(&pool, 3);

	// 监听socket
	int socket_fd;
	initSocket(&socket_fd, "192.168.169.128", "8080");

	int epoll_fd = epoll_create(1);
	addEpoll(epoll_fd, socket_fd);

	addEpoll(epoll_fd, pipe_fd[0]);
	while(1){
		
		struct epoll_event list[5];
		int epoll_num = epoll_wait(epoll_fd, list, 5, -1);
		

		for (int i = 0; i < epoll_num; i++){
			if(list->data.fd == pipe_fd[0]){
				// 有信号到父进程
				printf("我知道信号来了\n");
				char buf;
				read(pipe_fd[0], &buf, 1);

				pthread_mutex_lock(&pool.lock);
				pool.exitFlag = 1;
				pthread_cond_broadcast(&pool.cond);
				pthread_mutex_unlock(&pool.lock);

				for(int j = 0; j < pool.num; j++){
					pthread_join(pool.list[i], NULL);
				}
				
				printf("子线程都亖了\n");
				pthread_exit(NULL);


			}else if(list[i].data.fd == socket_fd){
				// 有新客户端到来
				int net_fd = accept(socket_fd, NULL, NULL);

				// V()生产者放入一个产品
				pthread_mutex_lock(&pool.lock);
				enQueue(&pool.queue, net_fd);
				// 广播唤醒
				pthread_cond_broadcast(&pool.cond);
				pthread_mutex_unlock(&pool.lock);
			}
		}
		
	}



	return 0;
}